{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Markov Networks\n",
    "\n",
    "author: Jacob Schreiber <br>\n",
    "contact: jmschreiber91@gmail.com\n",
    "\n",
    "Markov networks are probabilistic models that are usually represented as an undirected graph, where the nodes represent variables and the edges represent associations. Markov networks are similar to Bayesian networks with the primary difference being that Bayesian networks can be represented as directed graphs with known parental relations. Generally, Bayesian networks are easier to interpret and can be used to calculate probabilities faster but, naturally, require that causality is known. However, in many settings, one can only know the associations between variables and not necessarily the direction of causality.\n",
    "\n",
    "The underlying implementation of inference in pomegranate for both Markov networks and Bayesian networks is the same, because both get converted to their factor graph representations. However, there are many important differences between the two models that should be considered before choosing one. \n",
    "\n",
    "In this tutorial we will go over how to use Markov networks in pomegranate and what some of the current limitations of the implementation are."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mon Dec 02 2019 \n",
      "\n",
      "numpy 1.17.2\n",
      "scipy 1.3.1\n",
      "pomegranate 0.11.3\n",
      "\n",
      "compiler   : GCC 7.3.0\n",
      "system     : Linux\n",
      "release    : 4.15.0-66-generic\n",
      "machine    : x86_64\n",
      "processor  : x86_64\n",
      "CPU cores  : 8\n",
      "interpreter: 64bit\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import numpy\n",
    "import itertools\n",
    "\n",
    "from pomegranate import *\n",
    "\n",
    "numpy.random.seed(0)\n",
    "numpy.set_printoptions(suppress=True)\n",
    "\n",
    "%load_ext watermark\n",
    "%watermark -m -n -p numpy,scipy,pomegranate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Defining a Markov Network\n",
    "\n",
    "A Markov network is defined by passing in a list of the joint probability tables associated with a series of cliques rather than an explicit graph structure. This is because the probability distributions for a particular variable are not defined by themselves, but rather through associations with other variables. While a Bayesian network has root variables that do not hav e parents, the undirected nature of the edges in a Markov networks means that variables are generally grouped together.\n",
    "\n",
    "Let's define a simple Markov network where the cliques are A-B, B-C-D, and C-D-E. B-C-D-E is almost a clique but are missing the connection between B and E."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "d1 = JointProbabilityTable([\n",
    "    [0, 0, 0.1],\n",
    "    [0, 1, 0.2],\n",
    "    [1, 0, 0.4],\n",
    "    [1, 1, 0.3]], [0, 1])\n",
    "\n",
    "d2 = JointProbabilityTable([\n",
    "    [0, 0, 0, 0.05],\n",
    "    [0, 0, 1, 0.15],\n",
    "    [0, 1, 0, 0.07],\n",
    "    [0, 1, 1, 0.03],\n",
    "    [1, 0, 0, 0.12],\n",
    "    [1, 0, 1, 0.18],\n",
    "    [1, 1, 0, 0.10],\n",
    "    [1, 1, 1, 0.30]], [1, 2, 3])\n",
    "\n",
    "d3 = JointProbabilityTable([\n",
    "    [0, 0, 0, 0.08],\n",
    "    [0, 0, 1, 0.12],\n",
    "    [0, 1, 0, 0.11],\n",
    "    [0, 1, 1, 0.19],\n",
    "    [1, 0, 0, 0.04],\n",
    "    [1, 0, 1, 0.06],\n",
    "    [1, 1, 0, 0.23],\n",
    "    [1, 1, 1, 0.17]], [2, 3, 4])\n",
    "\n",
    "model = MarkovNetwork([d1, d2, d3])\n",
    "model.bake()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that the initialization is fairly straightforward. An important note is that the JointProbabilityTable object requires as the second argument a list of variables that are included in that clique in the order that they appear in the table, from left to right."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Calculating the probability of examples"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similar to the other probabilistic models in pomegranate, Markov networks can be used to calculate the probability or log probability of examples. However, unlike the other models, calculating the log probability for Markov networks is generally computationally intractable for data with even a modest number of variables (~30). \n",
    "\n",
    "The process for calculating the log probability begins by calculating the \"unnormalized\" log probability $\\hat{P}$, which is just the product of the probabilities for the variables $c$ in each clique $c \\in C$ under their joint probability table $JPT(c)$. This step is easy because it just involves, for each clique, taking the columns corresponding to that clique and performing a table lookup.\n",
    "\n",
    "\\begin{equation}\n",
    "\\hat{P}(X=x) = \\prod\\limits_{c \\in C} JPT(c)\n",
    "\\end{equation}\n",
    "\n",
    "The reason this is called the unnormalized probability is because the sum of all combinations of variables that $X$ can take $\\sum\\limits_{x \\in X} \\hat{P}(X=x)$ does not sum to 1; thus, it is not a true probability distribution. \n",
    "\n",
    "We can calculate the normalized probability $P(X)$ by dividing by the sum of probabilities under all combinations of variables, frequently referred to as the \"partition function\". Calculating the partition function $Z$ is as simple as summing the unnormalized probabilities over all possible combinations of variables $x \\in X$. \n",
    "\n",
    "\\begin{equation}\n",
    "Z = \\sum\\limits_{x \\in X} \\hat{P}(X=x)\n",
    "\\end{equation}\n",
    "\n",
    "Finally, we can divide any unnormalized probability calculation by the partition function to get the correct probability.\n",
    "\n",
    "\\begin{equation}\n",
    "P(X = x) = \\frac{1}{Z} \\hat{P}(X = x)\n",
    "\\end{equation}\n",
    "\n",
    "The `probability` method returns the normalized probability value. We can check this by seeing that it is different than simply passing the columns of data in to the distributions for their respective cliques."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.020425530968183916"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.probability([0, 1, 0, 0, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the probability if we simply passed the columns into the corresponding cliques:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0028800000000000006"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d1.probability([0, 1]) * d2.probability([1, 0, 0]) * d3.probability([0, 0, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, by passing the `unnormalized=True` parameter in to the `probability` method we can return the unnormalized probability values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0028799999999999997"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.probability([0, 1, 0, 0, 1], unnormalized=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that the two are identical, subject to machine precision."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Calculating the partition function\n",
    "\n",
    "Calculating the partition function involves summing the unnormalized probabilities of all combinations of variables that an example can take. Unfortunately, the time it takes to calculate the partition function grows exponentially with the number of dimensions. This means that it may not be able to calculate the partition function exactly for more than ~25 variables, depending on your machine. While pomegranate does not currently support any methods for calculating the partition function other than the exact method, it is flexible enough to allow users to get around this limitation.\n",
    "\n",
    "The partition function itself is calculated in the `bake` method because, at that point, all combinations of variables are known to the model. This value is then cached so that calls to `probability` or `log_probability` are just as fast regardless of if the normalized or unnormalized probabilities are calculated. However, if the user passes in `calculate_partition=False` the model will not spend time calculating the partition function. We can see the difference in time here:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.67 s ± 50.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n",
      "1.06 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
     ]
    }
   ],
   "source": [
    "X = numpy.random.randint(2, size=(100, 14))\n",
    "model2 = MarkovNetwork.from_samples(X)\n",
    "\n",
    "%timeit model2.bake()\n",
    "%timeit model2.bake(calculate_partition=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are two main reasons that one might not want to calculate the partition function when creating the model. The first is when the user will only be inspecting the model, such as after structure learning, or only doing inference, which uses the approximate loopy belief propogation. The second is if the user wants to estimate the partition function themselves using an approximate algorithm.\n",
    "\n",
    "Let's look at how one would manually calculate the exact partition function to see how an approximate algorithm could be substituted in. First, what happens if we don't calculate the partition but try to calculate probabilities?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "Must calculate partition before computing probability",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-253972a8e7bb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbake\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcalculate_partition\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprobability\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m~/Desktop/pomegranate/pomegranate/MarkovNetwork.pyx\u001b[0m in \u001b[0;36mpomegranate.MarkovNetwork.MarkovNetwork.probability\u001b[0;34m()\u001b[0m\n",
      "\u001b[0;32m~/Desktop/pomegranate/pomegranate/MarkovNetwork.pyx\u001b[0m in \u001b[0;36mpomegranate.MarkovNetwork.MarkovNetwork.log_probability\u001b[0;34m()\u001b[0m\n",
      "\u001b[0;31mValueError\u001b[0m: Must calculate partition before computing probability"
     ]
    }
   ],
   "source": [
    "model.bake(calculate_partition=False)\n",
    "model.probability([0, 1, 0, 0, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks like we get an error. We can still calculate unnormalized probabilities though."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0028799999999999997"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.probability([0, 1, 0, 0, 1], unnormalized=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can calculate the partition function by calculating the unnormalized probability of all combinations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.141"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Z = model.probability(list(itertools.product(*model.keys_)), unnormalized=True).sum()\n",
    "Z"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can set the stored partition function in the model to be this value (or specifically the log partition function) and then calculate normalized probabilities as before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.020425530968183916"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.partition = numpy.log(Z)\n",
    "model.probability([0, 1, 0, 0, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you can calculate $Z$ however you'd like and simply plug it in."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Inference\n",
    "\n",
    "Similar to Bayesian networks, Markov networks can be used to infer missing values in data sets. In pomegranate, inference is done for Markov networks by converting them to their factor graph representations and then using loopy belief propagation. This results in fast, but approximate, inference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([1, 1, 0, 1, 1], dtype=object), array([1, 1, 1, 1, 0], dtype=object)]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict([[None, 1, 0, None, None], [None, None, 1, None, 0]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we go back and inspect the joint probability tables we can easily see that the inferred values are the correct ones.\n",
    "\n",
    "If we want the full probability distribution rather than just the most likely value we can use the `predict_proba` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([{\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"dtype\" :\"int\",\n",
       "     \"name\" :\"DiscreteDistribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"0\" :0.37654171704957684,\n",
       "             \"1\" :0.623458282950423\n",
       "         }\n",
       "     ],\n",
       "     \"frozen\" :false\n",
       " },\n",
       "        {\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"dtype\" :\"int\",\n",
       "     \"name\" :\"DiscreteDistribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"0\" :0.11729141475211632,\n",
       "             \"1\" :0.8827085852478838\n",
       "         }\n",
       "     ],\n",
       "     \"frozen\" :false\n",
       " },\n",
       "        1,\n",
       "        {\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"dtype\" :\"int\",\n",
       "     \"name\" :\"DiscreteDistribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"0\" :0.08222490931076197,\n",
       "             \"1\" :0.917775090689238\n",
       "         }\n",
       "     ],\n",
       "     \"frozen\" :false\n",
       " },\n",
       "        0], dtype=object)]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba([[None, None, 1, None, 0]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Structure Learning\n",
    "\n",
    "Markov networks can be learned from data just as Bayesian networks can. While there are many algorithms that have been proposed for Bayesian network structure learning, there are fewer for Markov networks. Currently, pomegranate only supports the Chow-Liu tree-building algorithm for learning a tree-like network. Let's see a simple example where we learn a Markov network over a chunk of features from the digits data set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-12699.71644426486, -13141.625038482453)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.datasets import load_digits\n",
    "\n",
    "X = load_digits().data[:, 22:40]\n",
    "X = (X > numpy.median(X)).astype(int)\n",
    "\n",
    "model = MarkovNetwork.from_samples(X)\n",
    "icd = IndependentComponentsDistribution.from_samples(X, distributions=DiscreteDistribution)\n",
    "\n",
    "model.log_probability(X).sum(), icd.log_probability(X).sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like the Markov network is somewhat better than simply modeling each pixel individually for this set of features."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
